/**
 * @description  模板设置
 * @author swl
 */
import React, { PropTypes, PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Popconfirm, message } from 'antd';
import { TableC, DATA_ENTRY, AdvancedSearch, PrimaryGhostC, PrimaryC, ModalC, InputC, SecondHeaderC, IconC } from '../../comps';
import styles from './index.less';

@Form.create()
class ModelSettings extends PureComponent {
  state = {
    isEditTitle: '', // 模板名称编辑
    isEdit: false, // 表格编辑
    visible: false,
    tableList: [],
    tableListTemplate: [],
    modelId: 1, // 系统默认
    isSystem: 1, // 是否为系统默认
    modelName: '系统默认',
    modelList: [], // 模板设置
    managerId: '', // 租户id
    columns: [{ title: '模板名称', key: 'name', dataIndex: 'name', align: 'left' }],
    basicdataSource: [],
    moneydataSource: [],
    basicSelectedRowKeys: [], // 表格checkbox选择
    basicSelectedRows: [], // 表格checkbox选择
    moneySelectedRowKeys: [],
    moneySelectedRows: [],
  };

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    this.getModelsList();
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}

  componentWillUnmount() {}

  // 获取下拉数据源
  getModelsList = (e) => {
    this.props.dispatch({
      type: 'stressTestReportSettingsM/getModels',
      payload: {
        userName: 'default_maat_user_in_evar',
        orgCode: 'ZCTGB',
        systemCode: 'maat',
      },
      callback: (data) => {
        let managerId = '';
        data.map((item) => {
          if (item.MANAGER_ID && !managerId) {
            managerId = item.MANAGER_ID;
          }
          item.value = item.ID;
          item.title = item.C_TEMPLATE_NAME;
        });
        this.setState({
          modelList: data, // 初始化下拉数据
          managerId,
        });
        if (!(data != undefined && data.length > 0)) return;
        if (e) {
          this.modelSearch.props.form.setFieldsValue({
            modelId: e,
          });
          const temp = data.filter((item) => {
            return item.value === e;
          });
          this.setState({
            modelId: e,
            modelName: temp[0].title,
            isSystem: temp[0].IS_SYSTEM,
          });
        } else {
          const temp = data.filter((item) => {
            return item.value === 1;
          });
          this.modelSearch.props.form.setFieldsValue({
            modelId: temp[0].value,
          });
          this.setState(
            {
              modelId: temp[0].value,
              modelName: temp[0].title,
              isSystem: temp[0].IS_SYSTEM,
            },
            () => {
              this.getModelInfo();
            },
          );
        }
      },
    });
  };

  // 获取模板设置信息
  getModelInfo = () => {
    const { modelId } = this.state;
    this.props.dispatch({
      type: 'stressTestReportSettingsM/getModelInfo',
      payload: {
        templateId: modelId,
      },
      callback: (data) => {
        const basicSelected = [];
        const moneySelected = [];
        data.base.map((item) => {
          if (item.isSelect) {
            basicSelected.push(item.id);
          }
        });
        data.cash.map((item) => {
          if (item.isSelect) {
            moneySelected.push(item.id);
          }
        });
        this.setState({
          basicdataSource: data.base,
          moneydataSource: data.cash,
          basicSelectedRowKeys: basicSelected,
          moneySelectedRowKeys: moneySelected,
        });
      },
    });
  };

  // 查询条件
  renderForm = () => {
    const { modelList } = this.state;
    const {} = this.props;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'modelId',
          title: '模板名称',
          type: DATA_ENTRY.SELECT,
          allowClear: false,
          dataSource: modelList.map((item) => {
            const obj = {
              title: item.title,
              value: item.value,
            };
            return obj;
          }),
          filterOption: (input, option) => option.props.children.indexOf(input) > -1,
          onChange: (e) => {
            const selectValue = modelList.filter((data) => data.value == e);
            this.setState(
              {
                modelId: e,
                modelName: selectValue[0].title,
                isEdit: false,
                isSystem: selectValue[0].IS_SYSTEM,
              },
              () => {
                this.getModelInfo();
              },
            );
          },
        },
      ],
      selfButt: (
        <div className='scene-btn'>
          <IconC isHover={false} type={'plus'} title='新增' onClick={(e) => this.addModel()} />
          <IconC isHover={false} type={'edit'} title='编辑' onClick={(e) => this.editModel()} />
          <Popconfirm
            title='确定删除？'
            icon={<QuestionCircleOutlined />}
            onConfirm={(e) => {
              this.deleteModel();
            }}
          >
            <IconC isHover={false} type={'deleteBlue'} title='删除' />
          </Popconfirm>
        </div>
      ),
      allowClear: false,
      allowQuery: false,
      onRef: (ref) => {
        this.modelSearch = ref;
      },
    };

    return (
      <div>
        <AdvancedSearch {...searchProps} />
      </div>
    );
  };

  // 新增模板名称
  addModel = () => {
    this.setState(
      {
        visible: true,
        isEditTitle: false,
      },
      () => {
        if (this.state.modelNameRef) {
          this.state.modelNameRef.props.form.setFieldsValue({
            modelName: '',
          });
        }
      },
    );
  };

  // 编辑模板名称
  editModel = () => {
    if (this.state.isSystem == 1) {
      message.error('系统默认名称无法修改');
    } else {
      this.setState(
        {
          visible: true,
          isEditTitle: true,
        },
        () => {
          if (this.state.modelNameRef) {
            this.state.modelNameRef.props.form.setFieldsValue({
              modelName: this.state.modelName,
            });
          }
        },
      );
    }
  };

  // 模板名称保存
  addInfo = () => {
    const name = this.state.modelNameRef.props.form.getFieldsValue().modelName;
    if (this.state.isEditTitle && this.state.modelName == name) {
      this.setState({
        visible: false,
        isEditTitle: false,
      });
      message.success('保存成功！');
    } else {
      this.props.dispatch({
        type: 'stressTestReportSettingsM/checkModelName',
        payload: {
          orgCode: 'ZCTGB',
          templateName: name,
        },
        callback: (data) => {
          this.setState({
            visible: false,
          });
          if (data) {
            if (this.state.isEditTitle) {
              this.setState({
                isEditTitle: false,
              });
              this.props.dispatch({
                type: 'stressTestReportSettingsM/modelSettingsEditModelName',
                payload: {
                  templateName: name, // 模板名称
                  templateId: this.state.modelId,
                  userName: 'default_maat_user_in_evar',
                  orgCode: 'ZCTGB',
                },
                callback: (res) => {
                  message.success('编辑成功！');
                  this.getModelsList(this.state.modelId);
                },
              });
            } else {
              this.props.dispatch({
                type: 'stressTestReportSettingsM/modelSettingsSave',
                payload: {
                  templateName: name,
                  userName: 'default_maat_user_in_evar',
                  orgCode: 'ZCTGB',
                  systemCode: 'maat',
                  managerId: this.state.managerId,
                  baseModuleList: '1,2,3,5,6,8,4,7,9',
                  cashModuleList: '10,11,12,13,14,15',
                },
                callback: (res) => {
                  message.success('添加成功！');
                  this.props.dispatch({
                    type: 'stressTestReportSettingsM/getModels',
                    payload: {
                      userName: 'default_maat_user_in_evar',
                      orgCode: 'ZCTGB',
                      systemCode: 'maat',
                    },
                    callback: (data) => {
                      let managerId = '';
                      data.map((item) => {
                        if (item.MANAGER_ID && !managerId) {
                          managerId = item.MANAGER_ID;
                        }
                        item.value = item.ID;
                        item.title = item.C_TEMPLATE_NAME;
                      });
                      this.setState({
                        modelList: data, // 初始化下拉数据
                        managerId,
                      });
                      if (!(data != undefined && data.length > 0)) return;
                      const temp = data.filter((item) => {
                        return item.title === name;
                      });
                      this.modelSearch.props.form.setFieldsValue({
                        modelId: temp[0].value,
                      });
                      this.setState(
                        {
                          modelId: temp[0].value,
                          modelName: temp[0].title,
                          isSystem: temp[0].IS_SYSTEM,
                        },
                        () => {
                          this.getModelInfo();
                        },
                      );
                    },
                  });
                },
              });
            }
          }
        },
      });
    }
  };

  deleteModel = () => {
    if (this.state.isSystem == 1) {
      message.error('系统默认名称无法删除');
    } else {
      this.props.dispatch({
        type: `stressTestReportSettingsM/judgeUsageStatus`,
        payload: {
          modelId: this.state.modelId,
        },
        callback: (data) => {
          if (!data.dataSource.inUse) {
            this.setState({
              isEdit: false,
            });
            this.props.dispatch({
              type: `stressTestReportSettingsM/modelSettingsDelete`,
              payload: {
                templateId: this.state.modelId,
              },
              callback: (data) => {
                if (data.code === 0 && data.data) {
                  message.success('删除成功！');
                  this.getModelsList();
                }
              },
            });
          } else {
            message.error('当前情景名称已有租户使用，无法删除');
          }
        },
      });
    }
  };

  // 编辑表格
  editBtn = () => {
    this.setState({
      isEdit: true,
    });
  };

  // 保存
  saveBtn = () => {
    this.props.dispatch({
      type: 'stressTestReportSettingsM/modifyTemplateModule',
      payload: {
        templateId: this.state.modelId,
        baseModuleList: this.state.basicSelectedRowKeys.toString(),
        cashModuleList: this.state.moneySelectedRowKeys.toString(),
      },
      callback: (res) => {
        if (res) {
          message.success('修改成功！');
          this.getModelInfo();
          this.exitBtn();
        }
      },
    });
  };

  // 取消
  exitBtn = () => {
    this.getModelInfo();
    this.setState({
      isEdit: false,
    });
  };

  // 列表点击响应
  onbasicSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      basicSelectedRowKeys: selectedRowKeys,
      basicSelectedRows: selectedRows,
    });
  };

  onmoneySelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      moneySelectedRowKeys: selectedRowKeys,
      moneySelectedRows: selectedRows,
    });
  };

  render() {
    const {
      modelName,
      visible,
      isEdit,
      isEditTitle,
      columns,
      basicdataSource,
      moneydataSource,
      basicSelectedRowKeys, // 表格checkbox选择
      moneySelectedRowKeys,
    } = this.state;
    const basicrowSelection = {
      selectedRowKeys: basicSelectedRowKeys,
      onChange: this.onbasicSelectChange,
      getCheckboxProps: (record) => {
        return { disabled: !isEdit };
      },
    };
    const moneyrowSelection = {
      selectedRowKeys: moneySelectedRowKeys,
      onChange: this.onmoneySelectChange,
      getCheckboxProps: (record) => {
        return { disabled: !isEdit };
      },
    };
    return (
      <div>
        {this.renderForm()}
        <div style={{ marginTop: '12px' }}>
          {isEdit ? (
            <div>
              <PrimaryGhostC onClick={() => this.saveBtn()} title='保存' style={{ marginRight: '12px' }} />
              <PrimaryGhostC onClick={() => this.exitBtn()} title='取消' />
            </div>
          ) : (
            <PrimaryC onClick={() => this.editBtn()} title='编辑' />
          )}
        </div>
        <div style={{ marginTop: '12px' }}></div>
        <div className='tablebox'>
          <div className='tablebox-left'>
            <SecondHeaderC title={'基础配置'} />
            <TableC columns={columns} dataSource={basicdataSource} rowKey='id' rowSelection={basicrowSelection} hidePage={true} />
          </div>
          <div className='tablebox-right'>
            <SecondHeaderC title={'现金管理类附加配置'} />
            <TableC columns={columns} dataSource={moneydataSource} rowKey='id' rowSelection={moneyrowSelection} hidePage={true} />
          </div>
        </div>
        <ModalC
          visible={visible}
          onOk={this.addInfo}
          onCancel={() => {
            this.setState({
              visible: !visible,
              isEditTitle: false,
            });
          }}
          title={isEditTitle ? '编辑' : '新增'}
          width={420}
          okText='确认'
        >
          <Form>
            <InputC
              title='模板名称'
              dataIndex='modelName'
              placeholder='请输入'
              initialValue={isEditTitle ? modelName : ''}
              form={this.props.form}
              rules={[{ required: true, message: `请输入名称` }]}
              onRef={(ref) => this.setState({ modelNameRef: ref })}
            />
          </Form>
        </ModalC>
      </div>
    );
  }
}
export default connect(({ stressTestReportSettingsM, loading }) => ({ stressTestReportSettingsM, loading }))(ModelSettings);
